package com.iot.inclinometer.ui;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.iot.inclinometer.R;
import com.iot.inclinometer.dao.IBaseInfoDao;
import com.iot.inclinometer.dao.ICorrectDataInfoDao;
import com.iot.inclinometer.dao.IDataInfoDao;
import com.iot.inclinometer.dao.ILeijiInfoDao;
import com.iot.inclinometer.dao.IObserveInfoDao;
import com.iot.inclinometer.dao.IRealInfoDao;
import com.iot.inclinometer.dao.impl.BaseInfoDaoImpl;
import com.iot.inclinometer.dao.impl.CorrectDataInfoDaoImpl;
import com.iot.inclinometer.dao.impl.DataInfoDaoImpl;
import com.iot.inclinometer.dao.impl.LeijiInfoDaoImpl;
import com.iot.inclinometer.dao.impl.ObserveInfoDaoImpl;
import com.iot.inclinometer.dao.impl.RealInfoDaoImpl;
import com.iot.inclinometer.pojo.BaseInfo;
import com.iot.inclinometer.pojo.ObserveInfo;
import com.iot.inclinometer.util.Common;
import com.iot.inclinometer.util.ContextApplication;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * “老项目”
 * 
 * @author ZSL
 */
public class OldProUI extends Activity {
	private TextView titleView;		//显示标题(产品型号)
	/** 新项目 */
	private ImageView newProBtn;
	/** 绘草图 */
	private ImageView paintBtn;
	/** 导出 */
	private ImageView outputBtn;
	/** 上传 */
	private ImageView uploadDBBtn;
	/**设置*/
	private ImageView configurationBtn;
	/** 退出 */
	private ImageView exitBtn;
	/** 删除该钻孔按钮 */
	private Button deleteProBtn;
	/** 进入监测 */
	private Button startMeasureBtn;
	/** 进入实测监测 */
	private Button r_startMeasureBtn;
	/** 工程名称控件 */
	private Spinner projectNameSp = null;
	/** 工点名称空间 */
	private Spinner itemNameSp = null;
	/** 钻孔编号控件 */
	private Spinner drillNumSp = null;

	private TextView viewDepth = null;

	private TextView viewMark1 = null;
	private TextView viewMark2 = null;
	private TextView viewMark3 = null;
	private TextView viewMark4 = null;

	private TextView locView = null;
	private TextView viewX = null;
	private TextView viewY = null;
	private TextView viewAzimuth = null;

	private ArrayAdapter<String> projectAdapter = null;

	private ArrayAdapter<String> itemAdapter = null;

	private ArrayAdapter<String> drillAdapter = null;

	private IBaseInfoDao baseInfoDao = new BaseInfoDaoImpl(this);
	
	private String model=null;    //产品型号
	private int lightGreen=Color.parseColor("#98FB98");
	private int lightRed=Color.parseColor("#FF3333");
	private IObserveInfoDao observeInfoDao = new ObserveInfoDaoImpl(this);
	private IDataInfoDao dataInfoDao = new DataInfoDaoImpl(this);
	private ICorrectDataInfoDao correctDataInfoDao=new CorrectDataInfoDaoImpl(this);
	private ILeijiInfoDao leijiInfoDao=new LeijiInfoDaoImpl(this);
	private IRealInfoDao realInfoDao=new RealInfoDaoImpl(this);

	/** 将孔深传给下一个Activity */
	private String _depth;
	/** 将基本ID传给下一个Activity */
	private int _baseId=0;
	/** 将工点名称传给下一个Activity */
	private String _itemName;
	/** 将钻孔编号传给下一个Activity */
	private String _drillNum;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.old_pro_activity);
		SharedPreferences sharedPreferences= ContextApplication.getAppContext().getSharedPreferences("configuration",0);
		model=sharedPreferences.getString("Model","");
		initView();
		setBtnListener();
		initMenu();

	}

	/**
	 * 初始化三级联动菜单
	 */
	private void initMenu() {
		try {
			initMenu1();
			initMenu2();
			initMenu3();
		} catch (Exception e) {

		}
	}

	private void initMenu1() throws Exception {
		// ---------------------初始化项目名称-start---------------------------
		Set<String> projectNameSet = new HashSet<String>(); // 保存不重复的项目名
		List<String> projectNames = new ArrayList<String>(); // 将Set集合转成List集合,从而放入适配器

		List<BaseInfo> allBaseInfo = this.baseInfoDao.selectBaseInfos();

		for (BaseInfo baseInfo : allBaseInfo) {
			projectNameSet.add(baseInfo.getProjectName());
		}
		for (String projectName : projectNameSet) {
			projectNames.add(projectName);
		}
		Collections.sort(projectNames);//顺序排列
		// 把数组导入到ArrayList中
		projectAdapter = new ArrayAdapter<String>(this,
				android.R.layout.simple_spinner_item, projectNames);
		projectAdapter
				.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		// 设置下拉菜单的风格
		projectNameSp.setAdapter(projectAdapter);
		// 绑定适配器
		projectNameSp.setPrompt("请选择项目名");
	}

	private void initMenu2() throws Exception {
		// **************************初始化二级联动菜单**start****************************
		List<String> allItemsList = new ArrayList<String>();
		if(projectNameSp.getSelectedItem()==null){
			
		}else{
			String selectedProject = projectNameSp.getSelectedItem().toString();
			Set<String> allItemsSet = new HashSet<String>();
			//List<String> allItemsList = new ArrayList<String>();
	
			List<BaseInfo> allItems = this.baseInfoDao
					.selectBaseInfos(selectedProject); // 通过选中的项目名来取得对应的记录，从而得出二级目录的数据
			for (BaseInfo baseInfo : allItems) {
				allItemsSet.add(baseInfo.getItemName());
			}
			for (String item : allItemsSet) {
				allItemsList.add(item);
			}
			Collections.sort(allItemsList);//顺序排列
		}
		// 把数组导入到ArrayList中
		itemAdapter = new ArrayAdapter<String>(this,
				android.R.layout.simple_spinner_item, allItemsList);
		itemAdapter
				.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		// 设置下拉菜单的风格
		itemNameSp.setAdapter(itemAdapter);
		// 绑定适配器
		itemNameSp.setPrompt("请选择工点名");		
		
		// **************************初始化二级联动菜单**end*************************
	}

	private void initMenu3() throws Exception {
		List<String> allDrillList = new ArrayList<String>();
		if(projectNameSp.getSelectedItem()==null){
			
		}else{
			String selectedProject = projectNameSp.getSelectedItem().toString();
			String selectedItem = itemNameSp.getSelectedItem().toString();
			Set<String> allDrillSet = new HashSet<String>();
			//List<String> allDrillList = new ArrayList<String>();

			List<BaseInfo> allDrills = this.baseInfoDao.selectBaseInfos(
					selectedProject, selectedItem);
			for (BaseInfo baseInfo : allDrills) {
				allDrillSet.add(baseInfo.getDrillNum());
			}
			for (String drillNum : allDrillSet) {
				allDrillList.add(drillNum);
			}
			Collections.sort(allDrillList);//顺序排列
		}
		
		drillAdapter = new ArrayAdapter<String>(this,
				android.R.layout.simple_spinner_item, allDrillList);
		drillAdapter
				.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		drillNumSp.setAdapter(drillAdapter);
		drillNumSp.setPrompt("请选择钻孔编号");
		initValue();
	}

	/**
	 * 为界面上的TextView控件赋值
	 */
	private void initValue() throws Exception {
		if(projectNameSp.getSelectedItem()==null){
			viewDepth.setText(0+"");
			viewMark1.setText("");
			viewMark2.setText(0+"");
			viewMark3.setText(0+"");
			viewMark4.setText(0+"");
			locView.setText("");
			viewX.setText(0+"");
			viewY.setText(0+"");
			viewAzimuth.setText(0+"");

			//为需要传递的参数赋值
			_depth ="";
			_baseId =0;
			_itemName="";
			_drillNum ="";
		}else{
			String selectedProject = projectNameSp.getSelectedItem().toString();
			String selectedItem = itemNameSp.getSelectedItem().toString();
			String selectedDrill = drillNumSp.getSelectedItem().toString();
			BaseInfo baseInfo = this.baseInfoDao.selectBaseInfos(selectedProject,
					selectedItem, selectedDrill);

			viewDepth.setText(baseInfo.getDepth());
			viewMark1.setText(baseInfo.getMark1());
			viewMark2.setText(baseInfo.getMark2());
			viewMark3.setText(baseInfo.getMark3());
			viewMark4.setText(baseInfo.getMark4());
			locView.setText(baseInfo.getLoc());
			viewX.setText(baseInfo.getX());
			viewY.setText(baseInfo.getY());
			viewAzimuth.setText(baseInfo.getAzimuth());

			//为需要传递的参数赋值
			_depth = baseInfo.getDepth();
			_baseId = baseInfo.getBaseId();
			_itemName=baseInfo.getItemName();
			_drillNum = baseInfo.getDrillNum();
		}
	}

	/**
	 * 初始化控件
	 */
	private void initView() {
		titleView=(TextView) findViewById(R.id.tv_top_title); 	//初始化标题
		String newTitle = Common.isEmpty(model)?"":"("+model+")";
		titleView.setText(titleView.getText()+ newTitle);
		
		newProBtn = (ImageView) findViewById(R.id.new_pro_btn);
		paintBtn = (ImageView) findViewById(R.id.paint_btn);
		outputBtn = (ImageView) findViewById(R.id.output_btn);
		uploadDBBtn = (ImageView) findViewById(R.id.uploaddbToServer_btn);
		configurationBtn = (ImageView) findViewById(R.id.configuration_btn);
		exitBtn = (ImageView) findViewById(R.id.exit_btn);
		deleteProBtn = (Button) findViewById(R.id.delete_pro_btn);
		deleteProBtn.setBackgroundColor(lightGreen);
		startMeasureBtn = (Button) findViewById(R.id.start_measure_btn);
		startMeasureBtn.setBackgroundColor(lightGreen);
		r_startMeasureBtn = (Button) findViewById(R.id.r_start_measure_btn);
		r_startMeasureBtn.setBackgroundColor(lightGreen);
		

		// -----------初始化需要赋值的控件-------------------
		projectNameSp = (Spinner) findViewById(R.id.project_name_spinner);
		itemNameSp = (Spinner) findViewById(R.id.item_name_spinner);
		drillNumSp = (Spinner) findViewById(R.id.drill_num_spinner);
		viewDepth = (TextView) findViewById(R.id.deep_of_hole_view);
		viewMark1 = (TextView) findViewById(R.id.mark1_view);
		viewMark2 = (TextView) findViewById(R.id.mark2_view);
		viewMark3 = (TextView) findViewById(R.id.mark3_view);
		viewMark4 = (TextView) findViewById(R.id.mark4_view);
		locView = (TextView) findViewById(R.id.loc_view);
		viewX = (TextView) findViewById(R.id.x_view);
		viewY = (TextView) findViewById(R.id.y_view);
		viewAzimuth= (TextView) findViewById(R.id.azimuth_view);
	}

	/**
	 * 设置事件监听
	 */
	private void setBtnListener() {
		newProBtn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent intent = new Intent(OldProUI.this, NewProUI.class);
				startActivity(intent);
				OldProUI.this.finish();
			}
		});
		paintBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent intent = new Intent(OldProUI.this, PaintProUI.class);
				startActivity(intent);
				OldProUI.this.finish();
			}
		});
		outputBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent intent = new Intent(OldProUI.this, OutputProUI.class);
				startActivity(intent);
				OldProUI.this.finish();
			}
		});
		uploadDBBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent intent = new Intent(OldProUI.this, UploadDBToServerUI.class);
				startActivity(intent);
				OldProUI.this.finish();
			}
		});
		configurationBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent intent = new Intent(OldProUI.this,ConfigurationLicenseUI.class);
				startActivity(intent);
			}
		});
		exitBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				sureDialog();
			}
		});
		deleteProBtn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				AlertDialog.Builder builder = new Builder(OldProUI.this);
				builder.setMessage("确定删除该钻孔吗？");
				builder.setTitle("提示");
				builder.setPositiveButton("确定",
						new android.content.DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog, int which) {
								if(_baseId==0){
									//老项目为空，弹出吐司，提示先新建项目
									Toast.makeText(OldProUI.this, "老项目为空，请先创建新项目！",
											Toast.LENGTH_LONG).show();
								}else{
									List<ObserveInfo> observeInfoList=observeInfoDao.selectObserverInfos(_baseId);
									for(ObserveInfo observeInfo:observeInfoList){
										int ob_id=observeInfo.getObserveId();
										dataInfoDao.deleteDataInfosByobId(ob_id);
										correctDataInfoDao.deleteDataInfosByobId(ob_id);
										leijiInfoDao.deleteLeijiInfosByobId(ob_id);
										observeInfoDao.deleteObserveInfoByobId(ob_id);
										realInfoDao.deleteRealInfosByobId(ob_id);
									}
									int flag = baseInfoDao.deleteByBaseId(_baseId);
									if (flag!=0) {
										Toast.makeText(OldProUI.this, "删除成功！",
												Toast.LENGTH_LONG).show();
										dialog.dismiss();
										_baseId=0;
										initMenu();
									}else{
										Toast.makeText(OldProUI.this, "删除失败！",
												Toast.LENGTH_LONG).show();
									}	
								}
							}
						});
				builder.setNegativeButton("取消",
						new android.content.DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog, int which) {
								dialog.dismiss();
							}
						});
				builder.create().show();
			}
		});
		startMeasureBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if(_baseId==0){
					//老项目为空，弹出吐司，提示先新建项目
					Toast.makeText(OldProUI.this, "老项目为空，请创建新项目后，再进入监测！",
							Toast.LENGTH_LONG).show();
				}else if(getSharedPreferences("configuration",0).getString("Tclib","").equals("")){
					
					//参数为空，弹出吐司，提示先设置参数
					Toast.makeText(OldProUI.this, "请设置参数后，再进入监测！",
							Toast.LENGTH_LONG).show();
				}else{
					Intent intent = new Intent(OldProUI.this, MeasureDataUI.class);
					intent.putExtra("depth", _depth);
					intent.putExtra("baseId", _baseId);
					intent.putExtra("itemName", _itemName);
					intent.putExtra("drillNum", _drillNum);
					intent.putExtra("from", "old");
					startActivity(intent);
					OldProUI.this.finish();
				}
			}
		});
		r_startMeasureBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if(_baseId==0){
					//老项目为空，弹出吐司，提示先新建项目
					Toast.makeText(OldProUI.this, "老项目为空，请创建新项目后，再进入监测！",
							Toast.LENGTH_LONG).show();
				}else if(getSharedPreferences("configuration",0).getString("Tclib","").equals("")){
					
					//参数为空，弹出吐司，提示先设置参数
					Toast.makeText(OldProUI.this, "请设置参数后，再进入监测！",
							Toast.LENGTH_LONG).show();
				}else{
					Intent intent = new Intent(OldProUI.this, r_MeasureDataUI.class);
					intent.putExtra("depth", _depth);
					intent.putExtra("baseId", _baseId);
					intent.putExtra("itemName", _itemName);
					intent.putExtra("drillNum", _drillNum);
					intent.putExtra("from", "old");
					startActivity(intent);
					OldProUI.this.finish();
				}
			}
		});
		projectNameSp.setOnItemSelectedListener(new OnItemSelectedListener() {
			@Override
			public void onItemSelected(AdapterView<?> parent, View view,
					int position, long id) {
				try {
					initMenu2();
					initMenu3();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}

			@Override
			public void onNothingSelected(AdapterView<?> parent) {

			}

		});
		itemNameSp.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> parent, View view,
					int position, long id) {
				try {
					initMenu3();
				} catch (Exception exception) {
					exception.printStackTrace();
				}
			}

			@Override
			public void onNothingSelected(AdapterView<?> parent) {

			}
		});
		drillNumSp.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> parent, View view,
					int position, long id) {
				try {
					initValue();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}

			@Override
			public void onNothingSelected(AdapterView<?> parent) {
			}
		});

	}

	/** 监听返回按键 */
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
			sureDialog();
			return true;
		}
		return true;
	}

	/** 确认框 */
	public void sureDialog() {
		AlertDialog.Builder builder = new Builder(this);
		builder.setMessage("确定退出程序吗？");
		builder.setTitle("提示");
		builder.setPositiveButton("确定",
				new android.content.DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
						// AccoutList.this.finish();
						// System.exit(1);
						android.os.Process.killProcess(android.os.Process
								.myPid());
					}
				});
		builder.setNegativeButton("取消",
				new android.content.DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
					}
				});
		builder.create().show();
	}

}
